package day19;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class FlinkWordCount {
    public static void main(String[] args) throws Exception {
        // 构建flink开发环境;ExecutionEnviroment.getExecutionEnvironment()。。注意导入的包是java的那个org.apache.flink.api.java.ExecutionEnvironment;
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // 获取数据，生成数据：通过字符串构造数据集
        DataSource<String> text = env.fromElements(
                "hello zhangsan",
                "hello lisi",
                "hello wangwu"
        );


        // 切分
        FlatMapOperator<String, Tuple2<String, Integer>> pairs = text.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] splited = line.split(" ");
                for (String word : splited) {
                    out.collect(new Tuple2<String, Integer>(word, 1));
                }
            }
        });

        // 分组与聚合
        AggregateOperator<Tuple2<String, Integer>> sumed = pairs.groupBy(0).sum(1);

        // 打印
        sumed.print();

    }

}
